package com.confee.guanglai.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.confee.guanglai.domain.User;
import com.confee.guanglai.service.UserService;

@Controller
public class LoginController {
	
	@Autowired
	public UserService userService;
	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login( HttpServletRequest request, HttpServletResponse response,
			Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			return "login";
		}else{
			return "redirect:/index";
		}
		
	}
	
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(String no, String password, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			user = userService.findByNo(no);
			if(user != null && (user.getPassword()).equals(password)){
				request.getSession().setAttribute("user", user);
			}else{
				model.addAttribute("errorMsg", "工号或者密码错误，请重新登录");
				model.addAttribute("alertClass", "alert-error");
				return "login";
			}
		}
		return "redirect:/index";
	}


}
